package com.by.yz.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.by.yz.R;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.adapter.GridAdapter;
import com.by.yz.custom.MyGridView;
import com.by.yz.entity.Department;
import com.by.yz.loginUtil.DepartmentRESTFul;
import com.by.yz.util.ToJSonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.view.View.OnTouchListener;

/**
 * Created by John on 2016/10/13.
 */
public class FindDoctorActivity extends BaseActivity implements View.OnClickListener{
    private EditText look_auto;
    private TextView search;  //查找
    private LinearLayout chinese_doctor_layout; //中医科
    private LinearLayout skin_doctor_layout;  //皮肤科
    private LinearLayout children_doctor_layout;//儿科
    private LinearLayout orthopedics_doctor_layout; //骨伤科
    private LinearLayout gynaecology_doctor_layout; //妇科
    private LinearLayout surgery_doctor_layout;  //外科
    private LinearLayout main_layout;
    private String text;
    private MyGridView gv;
    private GridAdapter adapter;
    private List<Map<String,Object>> list;
    private static int keshiNum;
    private static int oldnum;
    private static int num;
    private static List<String> keshiName;
    private TextView moreList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("--onCreate--","onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_doctor);
        setToolbarTitle("找医生");
        keshiName =new ArrayList<String>();
        oldnum = 0;
        num = 9;
        initView();
        initDatas();
    }

    private void initView() {
        Log.e("--initView--","initView");
        look_auto = (EditText) findViewById(R.id.look_auto);
        search = (TextView) findViewById(R.id.lv_look);
        search.setOnClickListener(this);
        moreList = (TextView) findViewById(R.id.moreList);
        moreList.setOnClickListener(this);
//        chinese_doctor_layout = (LinearLayout) findViewById(R.id.chinese_doctor_layout);
//        skin_doctor_layout = (LinearLayout) findViewById(R.id.skin_doctor_layout);
//        children_doctor_layout = (LinearLayout) findViewById(R.id.children_doctor_layout);
//        orthopedics_doctor_layout = (LinearLayout) findViewById(R.id.orthopedics_doctor_layout);
//        gynaecology_doctor_layout = (LinearLayout) findViewById(R.id.gynaecology_doctor_layout);
//        surgery_doctor_layout = (LinearLayout) findViewById(R.id.surgery_doctor_layout);
        main_layout = (LinearLayout) findViewById(R.id.main_layout);
        main_layout.setOnClickListener(this);
        gv = (MyGridView) findViewById(R.id.gridview);
        gv.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE :
                        Log.e("onTouch","true");
                        return true;
                }
                Log.e("onTouch","false");
                return false;
            }
        });

        list = new ArrayList<Map<String,Object>>();

        if(isNetworkAvailable(FindDoctorActivity.this)){
            DepartmentRESTFul DepartmentREST=new DepartmentRESTFul();
            DepartmentREST.getAllDepartments(new DepartmentRESTFul.MyGETCallBack() {
                @Override
                public void ok(JSONArray response) throws JSONException {
                    keshiNum = response.length();
                    for (int i = 0; i < keshiNum; i++) {
                        Department department;
                        JSONObject jsonObject = response.getJSONObject(i);
                        department = ToJSonObject.jsonToBean(jsonObject.toString(), Department.class);
                        keshiName.add(i,department.getDepartment());
                    }
                    gridList();
                }
                @Override
                public void error(String error) {
                    Log.e("error",error);
                }
            });

        }else{//无网络连接情况
            new AlertDialog.Builder(FindDoctorActivity.this)
                    .setTitle("提示!")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setMessage("检测到您还没开启网络，请开启")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("开启",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    startActivity(new Intent(
                                            Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                                }
                            }).show();
        }

    }

    private void initDatas() {}

    void gridList(){
        Bundle b = new Bundle();
        try{Map<String,Object> map = null;
            for(int i=oldnum;i<num;i++){
                map = new HashMap<String,Object>();
                map.put("image", R.mipmap.login_logo);
                map.put("text", keshiName.get(i));
                map.put("Type", 1);
                list.add(map);
            }
            b.putBoolean("bindGrid", true);
        }catch(Exception e){}finally{
            Message msg = handler.obtainMessage();
            msg.setData(b);
            handler.sendMessage(msg);
        }
    }

    @Override
    public void onClick(View v) {
        InputMethodManager imm;
        switch (v.getId()) {
            case R.id.lv_look:
                text = look_auto.getText().toString().trim();
                if (!text.equals("")) {
                    intentData(text);
                } else {
                    Toast.makeText(FindDoctorActivity.this, "请输入查找内容", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.main_layout:
                /*关闭输入入法窗口*/
                imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(look_auto.getWindowToken(),0);
                break;
            case R.id.moreList:
                moreList.setVisibility(View.INVISIBLE);
                oldnum=num;
                num=keshiNum;
                gridList();
                break;
            default:
                break;
        }
    }
    private void intentData(String text) {
            Intent intent = new Intent(FindDoctorActivity.this, FindDoctorResultActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("searchString", text);
            intent.putExtras(bundle);
            FindDoctorActivity.this.startActivity(intent);
    }

    private void bindGrid(){
        adapter = new GridAdapter(this, list);
        gv.setAdapter(adapter);
    }

    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            try{
                if(msg.getData().containsKey("bindGrid")){
                    bindGrid();
                }
            }catch(Exception e){}
        }
    };
    /*
 * 判断是否有网络
 */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        } else {
            // 如果仅仅是用来判断网络连接　　　　　　
            // 则可以使用 cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null) {
                Log.e("hj","isNetworkAvailable - 是否有网络： "+ networkInfo.isAvailable());
                return true;
            } else {
                Log.e("hj", "isNetworkAvailable - 完全没有网络！");
                return false;
            }
        }
    }
}
